package org.example.service.impl;

import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderJdbcTemplateServiceImpl implements OrderService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final String MYSQL_CREATE_TABLE =
            "CREATE TABLE IF NOT EXISTS t_order (order_id BIGINT NOT NULL, user_id INT NOT NULL, address_id BIGINT NOT NULL, status VARCHAR(50), PRIMARY KEY (order_id))";

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.XA)
    public void insertDatas() {
//        jdbcTemplate.execute(MYSQL_CREATE_TABLE);
//        jdbcTemplate.execute("truncate table t_order");
        String sql = "INSERT INTO t_order (order_id, user_id, address_id, status) VALUES (?, ?, ?, ?)";
        List<Object[]> batchArgs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Object[] arg = new Object[]{i, i, i, "INIT"};
            batchArgs.add(arg);
        }
        jdbcTemplate.batchUpdate(sql, batchArgs);

        List<Map<String, Object>> data = jdbcTemplate.queryForList("SELECT * FROM t_order");
        if (data.isEmpty()) {
            System.out.println("t_order is empty");
            return;
        }
        for (Map<String, Object> each : data) {
            System.out.println(each.toString());
        }
    }
}
